﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using HelloLLLLL.Blog.Models;
using HelloLLLLL.Blog.Common;
using Newtonsoft.Json;
using HelloLLLLL.Blog.DAL;
using System.Data;

namespace HelloLLLLL.Blog
{
    /// <summary>
    /// FrontEnd 的摘要说明
    /// </summary>
    public class FrontEnd : IHttpHandler, IRequiresSessionState
    {
        DBHelper helper = new DBHelper();
        public void ProcessRequest(HttpContext context)
        {


            context.Response.ContentType = "application/json";
            string action = context.Request.QueryString["action"];
            var req = context.Request;
            var resp = context.Response;
            if (string.Compare(action, "leaveComment", false) == 0)
            {
                Pinglun pl = new Pinglun();

                pl.Email = req["personEmail"];
                pl.Content = req["EditorContent"];
                pl.ArtId = int.Parse(req["artId"]);
                pl.Pubnisher = req["nick"];
                if (pl.Pubnisher == "")
                {
                    pl.Pubnisher = "Anonymous";
                }
                pl.PubnishTime = DateTime.Now;
                pl.Home = req["personHome"];
                pl.ArtTitle = req["artTitle"];

                //string userAgent = req.UserAgent == null ? "无" : req.UserAgent;
                pl.VisSoft = req.Browser.Type;
                pl.VisSystem = req.Browser.Platform;

                string sql = SqlBuilderHelper.InsertSql<Pinglun>(pl, "Pinglun");

                int res = helper.GetNonQuery(sql);

                if (res > 0) {
                    string sqlCount = "select CommentCount from LLArticle where Id=" + pl.ArtId;
                    int commentCount = Convert.ToInt32(helper.GetScalar(sqlCount, null));

                    commentCount += 1;

                    string sqlInsert= "update LLArticle set CommentCount="+commentCount+ "where Id = " + pl.ArtId;
                    helper.GetNonQuery(sqlInsert);

                context.Response.ContentType = "application/json";
                resp.Write(JsonConvert.SerializeObject(new { code = 1, msg = "感谢您的评论！" })); }
                else
                {
                    resp.Write(JsonConvert.SerializeObject(new { code = 0, msg = "访问出现了问题" }));
                }
            
                resp.End();
            }
            else if (string.Compare(action, "replyComment", false) == 0)
            {
                //{"artId":"9","artTitle":"测试测试","nick":"sdfads","personEmail":"dsfsd","personHome":"adfadw","targetUserId":"","replyContent":"sdfd"}
                Pinglun pl = new Pinglun();

                pl.Email = req["personEmail"];
                pl.Content = req["replyContent"];
                pl.ArtId = int.Parse(req["artId"]);
                pl.Pubnisher = req["nick"];
                pl.ReplyId = int.Parse(req["targetUserId"]);
                if (pl.Pubnisher == "")
                {
                    pl.Pubnisher = "Anonymous";
                }
                pl.PubnishTime = DateTime.Now;
                pl.Home = req["personHome"];
                pl.ArtTitle = req["artTitle"];

                //string userAgent = req.UserAgent == null ? "无" : req.UserAgent;
                pl.VisSoft = req.Browser.Type;
                pl.VisSystem = req.Browser.Platform;

                string sql = SqlBuilderHelper.InsertSql<Pinglun>(pl, "Pinglun");

                int res = helper.GetNonQuery(sql);

                if (res > 0)
                {
                    string sqlCount = "select CommentCount from LLArticle where Id=" + pl.ArtId;
                    int commentCount = Convert.ToInt32(helper.GetScalar(sqlCount, null));

                    commentCount += 1;

                    string sqlInsert = "update LLArticle set CommentCount=" + commentCount + "where Id = " + pl.ArtId;
                    helper.GetNonQuery(sqlInsert);

                    context.Response.ContentType = "application/json";
                    resp.Write(JsonConvert.SerializeObject(new { code = 1, msg = "回复成功" }));
                }
                else
                {
                    resp.Write(JsonConvert.SerializeObject(new { code = 0, msg = "访问出现了问题" }));
                }

                resp.End();
            }
            else if (string.Compare(action, "listArticle", false) == 0)
            {
                List<LLArticle> listAr = new List<LLArticle>();
                string p = context.Request["page"];
                string l = context.Request["limit"];
                string artType = context.Request["artType"];
                string recordTime = context.Request["recordTime"];
                int page = 1;
                if (!string.IsNullOrEmpty(p))
                    page = int.Parse(p);
                int limit = 12;
                if (!string.IsNullOrEmpty(l))
                    limit = int.Parse(l);

                DataTable tb = null;
                if (!string.IsNullOrWhiteSpace(artType)) {
                   

                    string sql = @"select * from(select  a.[Id]
                      ,[Title]
                      ,[HomeImg]
                      ,[Digest]
                      ,[ArtTime]
                      ,[LastUpdatetime]
                      ,[Content]
                      ,[ReadPwd]
                      ,[Editor]
                      ,[PresentCount]
                      ,[CommentCount]
                      ,[ReadCount]
                          ,[IsTop],row_number()over(order by a.id desc) as num from LLArticle  a join ArtiAndType  b on a.Id=b.ArtId where b.TypeId={0} ) as t where t.num>={1} and t.num<={2} ";

                   sql= string.Format(sql, artType,  (page - 1) * limit + 1, page * limit);

                    tb = helper.GetPageList(sql);

                }
                if (!string.IsNullOrWhiteSpace(recordTime))
                {


                    string sql = @"select * from(select  a.[Id]
                      ,[Title]
                      ,[HomeImg]
                      ,[Digest]
                      ,[ArtTime]
                      ,[LastUpdatetime]
                      ,[Content]
                      ,[ReadPwd]
                      ,[Editor]
                      ,[PresentCount]
                      ,[CommentCount]
                      ,[ReadCount]
                          ,[IsTop],row_number()over(order by a.id desc) as num from LLArticle  a   where convert(varchar(7),a.artTime,120) = '{0}' ) as t where   t.num>={1} and t.num<={2} ";

                    sql = string.Format(sql, recordTime, (page - 1) * limit + 1, page * limit);

                    tb = helper.GetPageList(sql);

                }
                else
                {
                    tb = helper.GetPageList("LLArticle", "Id", (page - 1) * limit + 1, page * limit);
                }

                listAr = new ModelHandler<LLArticle>().FillModel(tb);

                foreach (var ar in listAr)
                {
                    ar.ArtType = new List<int>();
                    ar.ArtTypeName = new List<string>();
                    string sql = "select a.TypeId ,b.TypeName from ArtiAndType a join LLArtType b on a.TypeId=b.Id where a.ArtId=" + ar.Id;
                    var dt = helper.GetDataTable(sql, null);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ar.ArtType.Add(Convert.ToInt32(dt.Rows[i][0]));
                        ar.ArtTypeName.Add(dt.Rows[i][1].ToString());
                    }
                   

                }
                context.Response.Write(JsonConvert.SerializeObject(new { code = 1, data=listAr }));
                context.Response.End();
            }
            else if (string.Compare(action, "addPresent", false) == 0)
            {
                string artId = req["artId"];

                string sql = "update LLArticle set PresentCount= PresentCount+1 where Id=" + artId;

                helper.GetNonQuery(sql);
            }
            else if (string.Compare(action, "leaveMessage", false) == 0)
            {
                LeaveMessage pl = new LeaveMessage();

                pl.Email = req["personEmail"];
                pl.Content = req["EditorContent"];
               
                pl.Pubnisher = req["nick"];
                if (pl.Pubnisher == "")
                {
                    pl.Pubnisher = "Anonymous";
                }
                pl.PubnishTime = DateTime.Now;
                pl.Home = req["personHome"];

                pl.VisSoft = req.Browser.Type;
                pl.VisSystem = req.Browser.Platform;

                string sql = SqlBuilderHelper.InsertSql<LeaveMessage>(pl, "LeaveMessage");

                int res = helper.GetNonQuery(sql);

                if (res > 0)
                {
                   
                    context.Response.ContentType = "application/json";
                    resp.Write(JsonConvert.SerializeObject(new { code = 1, msg = "感谢您的留言！" }));
                }
                else
                {
                    resp.Write(JsonConvert.SerializeObject(new { code = 0, msg = "访问出现了问题" }));
                }

                resp.End();
            }
            else if (string.Compare(action, "replyMessage", false) == 0)
            {
                //{"artId":"9","artTitle":"测试测试","nick":"sdfads","personEmail":"dsfsd","personHome":"adfadw","targetUserId":"","replyContent":"sdfd"}
                LeaveMessage pl = new LeaveMessage();

                pl.Email = req["personEmail"];
                pl.Content = req["replyContent"];
                
                pl.Pubnisher = req["nick"];
                pl.ReplyId = int.Parse(req["targetUserId"]);
                if (pl.Pubnisher == "")
                {
                    pl.Pubnisher = "Anonymous";
                }
                pl.PubnishTime = DateTime.Now;
                pl.Home = req["personHome"];
              

                //string userAgent = req.UserAgent == null ? "无" : req.UserAgent;
                pl.VisSoft = req.Browser.Type;
                pl.VisSystem = req.Browser.Platform;

                string sql = SqlBuilderHelper.InsertSql<LeaveMessage>(pl, "LeaveMessage");

                int res = helper.GetNonQuery(sql);

                if (res > 0)
                {
                    context.Response.ContentType = "application/json";
                    resp.Write(JsonConvert.SerializeObject(new { code = 1, msg = "回复成功" }));
                }
                else
                {
                    resp.Write(JsonConvert.SerializeObject(new { code = 0, msg = "访问出现了问题" }));
                }

                resp.End();
            }
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}